#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/wait.h>

#define NUM 1024
#define SIZE 64
#define SEP " "
#define Noneredir 0
#define Inputredir 1
#define Outputredir 2
#define Appendredir 3
char cwd[1024];
char enval[1024];
int lastcode = 0;
int isredir = Noneredir;
char *FILE_NAME = NULL;
const char *getUsername()
{
    const char *r = getenv("USER");
    if (r == NULL)
        return "none";
    return r;
}
const char *homepath()
{
    const char *r = getenv("HOME");
    if (r == NULL)
        return "none";
    return r;
}
const char *getCwd()
{
    const char *r = getenv("PWD");
    if (r == NULL)
        return "none";
    return r;
}
void cd(const char *path)
{
    chdir(path);
    char tmp[SIZE];
    getcwd(tmp, sizeof(tmp));
    sprintf(cwd, "PWD=%s", tmp);
    putenv(cwd);
}
const char *getHostname()
{
    const char *r = getenv("HOSTNAME");
    if (r)
        return r;
    return "none";
}

int getusercommad(char *commad, int num)
{
    printf("[%s@%s %s]# ", getUsername(), getHostname(), getCwd());
    char *r = fgets(commad, num, stdin);
    if (r == NULL)
        return -1;
    commad[strlen(commad) - 1] = '\0';
    return strlen(commad);
}

int commadsplit(char *in, char *out[])
{
    int argc = 0;
    out[argc++] = strtok(in, SEP);
    while (out[argc++] = strtok(NULL, SEP))
        ;

    return 1;
}

int dobuildin(char *argv[])
{
    if (strcmp(argv[0], "cd") == 0)
    {
        const char *path;
        if (argv[1] == NULL)
            path = homepath();
        else
            path = argv[1];
        cd(path);
        return 1;
    }
    else if (strcmp(argv[0], "export") == 0)
    {
        if (argv[1] == NULL)
            return 1;
        strcpy(enval, argv[1]);
        putenv(enval);
        return 1;
    }
    else if (strcmp(argv[0], "echo") == 0)
    {
        if (argv[1] == NULL)
        {
            printf("\n");
            return 1;
        }
        if (*(argv[1]) == '$' && strlen(argv[1]) > 1)
        {
            char *tmp = argv[1] + 1;
            if (strcmp(tmp, "?") == 0)
            {
                printf("%d\n", lastcode);
                lastcode = 0;
            }
            else
            {
                const char *tmpenv = getenv(tmp);
                if (tmpenv == NULL)
                    printf("\n");
                printf("%s\n", tmpenv);
            }
            return 1;
        }
        else
        {
            printf("%s\n", argv[1]);
            return 1;
        }
    }
    else if (0)
    {
    }
    return 0;
}
#define srmspace(pos)         \
    do                        \
    {                         \
        while (isspace(*pos)) \
            pos++;            \
    } while (0)

void CheckRedir(char commad[])
{
    char *begin = commad;
    char *end = commad + strlen(commad) - 1;
    while (end > begin)
    {
        if (*end == '<')
        {
            *end = '\0';
            char *FILE_NAME = end + 1;
            srmspace(FILE_NAME);
            isredir = Inputredir;
            break;
        }
        else if (*end == '>')
        {

            if ((*(end - 1)) == '>')
            {
                FILE_NAME = end + 1;
                srmspace(FILE_NAME);
                *(end - 1) = '\0';
                isredir = Appendredir;
                break;
            }
            else
            {
                FILE_NAME = end + 1;
                srmspace(FILE_NAME);
                *(end) = '\0';
                isredir = Outputredir;
                break;
            }
        }
        else
        {
            end--;
        }
    }
}
int Excute(char *argv[])
{
    pid_t id = fork();
    if (id < 0)
        return -1;

    if (id == 0)
    {
        int fd = 0;
        if (isredir == Inputredir)
        {
            fd = open(FILE_NAME, O_RDONLY);
            dup2(fd, 0);
        }
        else if (isredir == Outputredir)
        {
            fd = open(FILE_NAME, O_CREAT | O_WRONLY | O_TRUNC, 0666);
            dup2(fd, 1);
        }
        else if (isredir == Appendredir)
        {
            fd = open(FILE_NAME, O_CREAT | O_WRONLY | O_APPEND, 0666);
            dup2(fd, 1);
        }
        execvp(argv[0], argv);
        exit(1);
    }
    else
    {
        int status;
        pid_t rid = waitpid(id, &status, 0);
        if (rid > 0)
            lastcode = WEXITSTATUS(status);
    }
    return 0;
}
int main()
{
    while (1)
    {
        isredir = Noneredir;
        FILE_NAME = NULL;
        char usercommad[NUM];
        char *argv[SIZE];
        int n = getusercommad(usercommad, sizeof(usercommad));
        if (n <= 0)
            continue;
        CheckRedir(usercommad);
        commadsplit(usercommad, argv);
        n = dobuildin(argv);
        if (n == 0)
            Excute(argv);
    }

    return 0;
}